package com.gitee.wsl.io.buffer.ext

import com.gitee.wsl.io.buffer.ByteBuffer
import com.gitee.wsl.io.buffer.ByteBufferBase


/**
 * Moves bytes from `this` buffer to the [destination] buffer
 *
 *
 * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.util.moveTo)
 *
 * @param destination is the buffer to copy bytes to
 * @param limit is an optional parameter specifying maximum number of bytes to be moved
 * @return number of bytes moved
 */
fun<Element, Array> ByteBufferBase<Element, Array>.moveTo(destination: ByteBufferBase<Element, Array>, limit: Int = Int.MAX_VALUE): Int {
    val size = minOf(limit, remaining, destination.remaining)
    if (size == remaining) {
        destination.put(this)
    } else {
        val l = limit
        this.limit = position + size
        destination.put(this)
        this.limit = l
    }
    return size
}

/**
 * Moves bytes from `this` buffer into newly created [ByteArray] and returns it
 *
 * [Report a problem](https://ktor.io/feedback/?fqname=io.ktor.util.moveToByteArray)
 */
fun ByteBuffer.moveToByteArray(): ByteArray {
    val array = ByteArray(remaining)
    get(array)
    return array
}